package com.example.demo.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DeepSeekAnswer {
//你是一个营养师，根据焦虑情绪推荐十个食物,每个食物有图片，名称，类型和描述
    public String getAnswer(String question)throws IOException {
        String apiKey = "sk-47236ad2f93d44e2b3bccddc1d37f0af";
        String apiUrl = "https://api.deepseek.com/v1/chat/completions";
        String answer=null;
        // 构造请求 JSON 全麦面包.png
        String jsonInputString = String.format("""
        {
                "model": "deepseek-chat",
                "messages": [
                  {"role": "user", "content": "你是一个营养师，根据%s情绪推荐十种食物,使用json格式，格式如下：[{'name':'食物名称','type':'食物类型','description':'食物描述'}]"}
                ],
                "temperature": 0.7
        }
        """,question);

        // 创建连接
        URL url = new URL(apiUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求方法和头部
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 发送请求
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        int code = conn.getResponseCode();
        if (code == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                answer =  response.toString();

            }
        } else {
            System.out.println("请求失败，HTTP 状态码：" + code);
        }
        return answer;
    }
}
